<template>
  <div class="buyer-home">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <h2>在线商城</h2>
      </div>
      <div class="header-center">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索商品"
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      <div class="header-right">
        <el-button @click="showCart = true">
          <el-icon><ShoppingCart /></el-icon>
          购物车
          <el-badge v-if="cartCount > 0" :value="cartCount" />
        </el-button>
        <el-dropdown @command="handleCommand">
          <el-button>
            <el-icon><User /></el-icon>
            {{ userInfo.username }}
            <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="personalInfo">修改个人信息</el-dropdown-item>
              <el-dropdown-item command="orders">我的订单</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-container class="main-container">
      <!-- 左侧分类导航 -->
      <el-aside width="200px" class="aside">
        <el-menu
          :default-active="activeCategory"
          @select="handleCategorySelect"
        >
          <el-menu-item index="all">
            <el-icon><Grid /></el-icon>
            <span>全部商品</span>
          </el-menu-item>
          <el-menu-item
            v-for="category in categories"
            :key="category.id"
            :index="category.id.toString()"
          >
            <el-icon><Folder /></el-icon>
            <span>{{ category.name }}</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 右侧商品展示 -->
      <el-main class="main">
        <div class="product-grid">
          <el-card
            v-for="product in products"
            :key="product.id"
            class="product-card"
            @click="showProductDetail(product)"
          >
            <div class="product-image">
              <el-image
                :src="getImageUrl(product.images) || '/default-product.jpg'"
                fit="cover"
                style="width: 100%; height: 200px"
              />
            </div>
            <div class="product-info">
              <h3>{{ product.name }}</h3>
              <p class="price">¥{{ product.price }}</p>
              <p class="description">{{ product.description }}</p>
              <div class="product-actions">
                <el-button
                  type="primary"
                  size="small"
                  @click.stop="addToCart(product)"
                >
                  加入购物车
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>

    <!-- 购物车抽屉 -->
    <el-drawer
      v-model="showCart"
      title="购物车"
      direction="rtl"
      size="400px"
    >
      <div class="cart-content">
        <div v-if="cartItems.length === 0" class="empty-cart">
          <el-empty description="购物车为空" />
        </div>
        <div v-else>
          <div
            v-for="item in cartItems"
            :key="item.id || item.productId"
            class="cart-item"
          >
            <el-image
              :src="item.productImage || item.images || '/default-product.jpg'"
              style="width: 60px; height: 60px"
            />
            <div class="cart-item-info">
              <h4>{{ item.productName }}</h4>
              <p>¥{{ item.productPrice }}</p>
            </div>
            <div class="cart-item-actions">
              <el-input-number
                v-model="item.quantity"
                :min="1"
                size="small"
                @change="updateCartQuantity(item.productId, item.quantity)"
              />
              <el-button
                type="danger"
                size="small"
                @click="removeFromCart(item.productId)"
              >
                删除
              </el-button>
            </div>
          </div>
          <div class="cart-footer">
            <div class="cart-total">
              总计: ¥{{ cartTotal }}
            </div>
            <el-button type="primary" @click="checkout">
              结算
            </el-button>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 商品详情对话框 -->
    <el-dialog
      v-model="showProductDialog"
      title="商品详情"
      width="600px"
    >
      <div v-if="selectedProduct" class="product-detail">
        <el-image
          :src="getImageUrl(selectedProduct.images) || '/default-product.jpg'"
          style="width: 100%; height: 300px"
        />
        <h3>{{ selectedProduct.name }}</h3>
        <p class="price">¥{{ selectedProduct.price }}</p>
        <p>{{ selectedProduct.description }}</p>
        <div class="product-detail-actions">
          <el-input-number
            v-model="purchaseQuantity"
            :min="1"
            :max="selectedProduct.stock"
          />
          <el-button type="primary" @click="addToCart(selectedProduct)">
            加入购物车
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 修改个人信息对话框 -->
    <el-dialog v-model="showPersonalInfoDialog" title="修改个人信息" width="400px">
      <el-form :model="personalInfoForm" :rules="personalInfoRules" ref="personalInfoFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="personalInfoForm.username" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="personalInfoForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="personalInfoForm.email" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="personalInfoForm.address" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPersonalInfoDialog = false">取消</el-button>
        <el-button type="primary" @click="submitPersonalInfo">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAllProducts,
  getProductsByCategory,
  searchProducts
} from '../api/product.js'
import {
  getCartList,
  addToCart as addToCartApi,
  updateCartQuantity as updateCartQuantityApi,
  deleteCartItem,
  getCartTotal
} from '../api/cart.js'
import { getAllCategories } from '../api/category.js'
import { getUserInfo, updateUserInfo } from '../api/user.js'
import { confirmOrder as confirmOrderApi, createOrderFromCart } from '../api/order.js'
import { 
  validateUserData, 
  formatUserInfoForSubmit, 
  validateUserInfo,
  processUserApiResponse 
} from '../utils/userUtils.js'
import axios from 'axios'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const activeCategory = ref('all')
const products = ref([])
const categories = ref([])
const showCart = ref(false)
const cartItems = ref([])
const cartCount = ref(0)
const cartTotal = ref(0)
const showProductDialog = ref(false)
const selectedProduct = ref(null)
const purchaseQuantity = ref(1)
const userInfo = ref({ username: '买家' })
const showPersonalInfoDialog = ref(false)
const personalInfoForm = reactive({ username: '', phone: '', email: '', address: '' })
const personalInfoFormRef = ref()
const personalInfoRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [{ 
    pattern: /^1[3-9]\d{9}$/, 
    message: '请输入正确的手机号码', 
    trigger: 'blur' 
  }],
  email: [{ 
    type: 'email', 
    message: '请输入正确的邮箱地址', 
    trigger: 'blur' 
  }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
}

// 方法
const loadProducts = async (categoryId = null) => {
  try {
    let res
    if (categoryId && categoryId !== 'all') {
      res = await getProductsByCategory(categoryId)
    } else {
      res = await getAllProducts()
    }
    products.value = res.data || []
  } catch (error) {
    console.error('加载商品失败:', error)
    ElMessage.error('加载商品失败')
  }
}

const loadCategories = async () => {
  try {
    const res = await getAllCategories()
    categories.value = res.data || []
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

const loadCart = async () => {
  try {
    const res = await getCartList()
    // 兼容处理
    cartItems.value = (res.data || []).map(item => ({
      ...item,
      id: item.id || item.productId, // 兼容id
      productImage: item.productImage || item.images || '', // 兼容图片
      price: item.productPrice // 兼容价格字段
    }))
    cartCount.value = cartItems.value.length

    const totalRes = await getCartTotal()
    cartTotal.value = totalRes.data || 0
  } catch (error) {
    console.error('加载购物车失败:', error)
  }
}

const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    await loadProducts(activeCategory.value)
    return
  }
  
  try {
    const res = await searchProducts(searchKeyword.value)
    products.value = res.data || []
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  }
}

const handleCategorySelect = async (index) => {
  activeCategory.value = index
  await loadProducts(index)
}

const addToCart = async (product) => {
  try {
    if (!userInfo.value.username || userInfo.value.username === '买家') {
      ElMessage.error('请先登录');
      return;
    }
    
    const quantity = purchaseQuantity.value || 1;
    
    await addToCartApi(product.id, quantity)
    ElMessage.success('添加成功')
    await loadCart()
    showProductDialog.value = false
  } catch (error) {
    console.error('添加购物车失败:', error)
    ElMessage.error(error.message || '添加失败')
  }
}

const updateCartQuantity = async (productId, quantity) => {
  try {
    await updateCartQuantityApi(productId, quantity)
    await loadCart()
  } catch (error) {
    console.error('更新数量失败:', error)
    ElMessage.error('更新失败')
  }
}

const removeFromCart = async (productId) => {
  try {
    await deleteCartItem(productId)
    ElMessage.success('删除成功')
    await loadCart()
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

const checkout = async () => {
  try {
    if (!userInfo.value.id) {
      ElMessage.error('请先登录');
      return;
    }
    
    if (cartItems.value.length === 0) {
      ElMessage.error('购物车为空，无法结算');
      return;
    }
    
    await ElMessageBox.confirm('确认结算购物车中的商品？', '提示')
    
    const res = await createOrderFromCart(userInfo.value.id)
    
    if (res.data && res.data.state === 200) {
      ElMessage.success('结算成功，订单已创建');
      await loadCart(); // 重新加载购物车
      showCart.value = false; // 关闭购物车抽屉
      router.push('/buyer/orders'); // 跳转订单页
    } else {
      ElMessage.success('结算成功，订单已创建');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('结算失败:', error);
      ElMessage.error(error.response?.data?.message || error.message || '结算失败，请稍后重试');
    }
  }
}

const showProductDetail = async (product) => {
  selectedProduct.value = product
  purchaseQuantity.value = 1
  showProductDialog.value = true
}

const loadUserInfo = async () => {
  try {
    const res = await getUserInfo()
    if (res && res.state === 200) {
      // 确保数据完整性，设置默认值
      const userData = {
        username: res.data.username || '买家',
        phone: res.data.phone || '',
        email: res.data.email || '',
        address: res.data.address || '',
        ...res.data
      }
      
      Object.assign(personalInfoForm, {
        username: userData.username,
        phone: userData.phone,
        email: userData.email,
        address: userData.address
      })
      userInfo.value = userData
    } else if (res && res.state === 401) {
      // 用户未登录，设置默认值
      userInfo.value = { username: '买家' }
      console.log('用户未登录')
    } else {
      // 设置默认值，避免页面显示错误
      userInfo.value = { username: '买家' }
      console.error('获取用户信息失败:', res)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 设置默认值，避免页面显示错误
    userInfo.value = { username: '买家' }
    console.warn('获取用户信息失败，使用默认值')
  }
}

const submitPersonalInfo = async () => {
  try {
    const valid = await personalInfoFormRef.value.validate()
    if (!valid) return
    
    // 数据验证
    const submitData = {
      username: personalInfoForm.username?.trim() || '',
      phone: personalInfoForm.phone?.trim() || '',
      email: personalInfoForm.email?.trim() || '',
      address: personalInfoForm.address?.trim() || ''
    }
    
    // 验证必填字段
    if (!submitData.username) {
      ElMessage.error('用户名不能为空')
      return
    }
    
    await updateUserInfo(submitData)
    ElMessage.success('修改成功')
    showPersonalInfoDialog.value = false
    await loadUserInfo() // 重新加载用户信息
  } catch (error) {
    console.error('修改个人信息失败:', error)
    ElMessage.error('修改失败，请稍后重试')
  }
}

const handleCommand = (command) => {
  switch (command) {
    case 'personalInfo':
      showPersonalInfoDialog.value = true
      loadUserInfo()
      break
    case 'orders':
      router.push('/buyer/orders')
      break
    case 'logout':
      router.push('/login')
      break
  }
}

const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  if (imagePath.startsWith('data:')) {
    return imagePath
  }
  if (imagePath.startsWith('http')) {
    return imagePath
  }
  const path = imagePath.startsWith('/') ? imagePath : '/' + imagePath
  return `http://localhost:8080${path}`
}

const handleConfirmOrder = async (orderId) => {
  await confirmOrderApi(orderId)
  await loadOrders()
}

// 生命周期
onMounted(() => {
  loadProducts()
  loadCategories()
  loadCart()
  loadUserInfo()
})
</script>

<style scoped>
.buyer-home {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.header-left h2 {
  margin: 0;
  color: #409eff;
}

.header-center {
  flex: 1;
  max-width: 400px;
  margin: 0 20px;
}

.search-input {
  width: 100%;
}

.header-right {
  display: flex;
  gap: 10px;
}

.main-container {
  flex: 1;
  height: calc(100vh - 60px);
}

.aside {
  background: #fff;
  border-right: 1px solid #e4e7ed;
}

.main {
  padding: 20px;
  background: #f5f7fa;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.product-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-image {
  margin-bottom: 10px;
}

.product-info h3 {
  margin: 10px 0;
  font-size: 16px;
  color: #333;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin: 5px 0;
}

.description {
  color: #666;
  font-size: 14px;
  margin: 5px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.cart-content {
  padding: 20px;
}

.empty-cart {
  text-align: center;
  padding: 40px 0;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
}

.cart-item-info {
  flex: 1;
  margin-left: 10px;
}

.cart-item-info h4 {
  margin: 0 0 5px 0;
  font-size: 14px;
}

.cart-item-info p {
  margin: 0;
  color: #f56c6c;
  font-weight: bold;
}

.cart-item-actions {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.cart-footer {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-total {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.product-detail {
  text-align: center;
}

.product-detail h3 {
  margin: 15px 0;
  font-size: 20px;
}

.product-detail-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}
</style>